package cn.iphone.testTwo;

import cn.iphone.utils.ESClientUtil;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

public class EsTest {
    /**
     * 添加数据到ES
     * @throws Exception
     */
    @Test
    public void testAdd() throws Exception {
        for (int i = 1; i < 100; i++) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("age",i);
            map.put("name", i % 2 == 0 ? "张敏学吃粑粑" : "敏学爱吃屎");
            IndexResponse indexResponse = ESClientUtil.getClient().prepareIndex("es", "test", "" + i).setSource(map).get();
            System.out.println(indexResponse);
        }
    }

    /**
     * 查询数据
     * @throws Exception
     */
    @Test
    public void testGet() throws Exception {
        Map<String, Object> source = ESClientUtil.getClient().prepareGet("es", "test", "1").get().getSource();
        System.out.println(source);
    }

    /**
     * 修改数据
     * @throws Exception
     */
    @Test
    public void testUpt() throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        map.put("name","xxxxxx");
        UpdateResponse response = ESClientUtil.getClient().prepareUpdate("es", "test", "1").setDoc(map).get();
        System.out.println(response);
    }

    /**
     * 删除数据
     * @throws Exception
     */
    @Test
    public void testDelete() throws Exception {
        DeleteResponse response = ESClientUtil.getClient().prepareDelete("es", "test", "1").get();
        System.out.println(response);
    }

    /**
     * 复杂查询
     * @throws Exception
     */
    @Test
    public void testQuery() throws Exception {
        SearchRequestBuilder builder = ESClientUtil.getClient().prepareSearch("es").setTypes("test");
        BoolQueryBuilder filter = QueryBuilders.boolQuery().must(QueryBuilders.matchQuery("name", "敏学"))
                .filter(QueryBuilders.rangeQuery("age").gte(1).lte(50));
        SearchHit[] hits = builder.setQuery(filter).setFrom(5).setSize(5).addSort("age", SortOrder.ASC)
                .get().getHits().getHits();
        for (SearchHit hit : hits) {
            System.out.println(hit.getSourceAsMap());
        }
    }
}
